#include "pythoneditor.h"
#include <QDebug>

PythonEditor::PythonEditor(QWidget *parent)
    : BaseEditor(parent)
    , m_pythonLexer(nullptr)
    , m_pythonVersion(3)
{
    setupLanguage();
    setupCodeCompletion();
}

PythonEditor::~PythonEditor()
{
    // m_pythonLexer由基类管理，不需要手动删除
}

void PythonEditor::setupLanguage()
{
    setupPythonLexer();
    if (m_syntaxHighlightingEnabled) {
        setLexer(m_pythonLexer);
    }
}

void PythonEditor::setupCodeCompletion()
{
    setupPythonAPIs();
    setupPythonKeywords();
}

QStringList PythonEditor::getKeywords() const
{
    QStringList allKeywords;
    allKeywords += getPythonKeywords();
    allKeywords += getPythonBuiltins();
    allKeywords += m_customModules;
    return allKeywords;
}

LanguageType PythonEditor::getLanguageType() const
{
    return LanguageType::PYTHON;
}

void PythonEditor::checkSyntax()
{
    clearSyntaxErrors();

    QString text = getAllText();
    QStringList lines = text.split('\n');

    // 简单的Python语法检查示例
    int indentLevel = 0;

    for (int i = 0; i < lines.size(); ++i) {
        QString line = lines[i];
        QString trimmedLine = line.trimmed();

        if (trimmedLine.isEmpty() || trimmedLine.startsWith('#')) {
            continue;
        }

        // 检查缩进
        int currentIndent = 0;
        for (QChar c : line) {
            if (c == ' ') {
                currentIndent++;
            } else if (c == '\t') {
                currentIndent += 4; // 假设tab=4个空格
            } else {
                break;
            }
        }

        // 检查冒号后的缩进
        if (i > 0) {
            QString prevLine = lines[i-1].trimmed();
            if (prevLine.endsWith(':')) {
                if (currentIndent <= indentLevel) {
                    annotate(i, "Expected indent", QsciScintilla::AnnotationStandard);
                    emit syntaxErrorDetected(i, "Expected indent after ':'");
                }
                indentLevel = currentIndent;
            }
        }

        // 检查括号匹配
        int openParens = line.count('(');
        int closeParens = line.count(')');
        int openBrackets = line.count('[');
        int closeBrackets = line.count(']');
        int openBraces = line.count('{');
        int closeBraces = line.count('}');

        if (openParens != closeParens) {
            annotate(i, "Parenthesis mismatch", QsciScintilla::AnnotationStandard);
            emit syntaxErrorDetected(i, "Parenthesis mismatch");
        }

        if (openBrackets != closeBrackets) {
            annotate(i, "Bracket mismatch", QsciScintilla::AnnotationStandard);
            emit syntaxErrorDetected(i, "Bracket mismatch");
        }

        if (openBraces != closeBraces) {
            annotate(i, "Brace mismatch", QsciScintilla::AnnotationStandard);
            emit syntaxErrorDetected(i, "Brace mismatch");
        }

        // 检查常见的语法错误
        if (trimmedLine.contains("print ") && m_pythonVersion == 3) {
            annotate(i, "Use print() function in Python 3", QsciScintilla::AnnotationStandard);
            emit syntaxErrorDetected(i, "Use print() function in Python 3");
        }
    }
}

void PythonEditor::addCustomModules(const QStringList &modules)
{
    m_customModules += modules;
    if (m_apis) {
        for (const QString &module : modules) {
            m_apis->add(module);
        }
        m_apis->prepare();
    }
}

void PythonEditor::setPythonVersion(int version)
{
    if (version == 2 || version == 3) {
        m_pythonVersion = version;
        setupCodeCompletion(); // 重新设置代码补全
    }
}

void PythonEditor::setupPythonLexer()
{
    m_pythonLexer = new QsciLexerPython(this);
    m_lexer = m_pythonLexer;

    // 设置Python语言特性
    m_pythonLexer->setFoldComments(true);
    m_pythonLexer->setFoldQuotes(true);

    // 设置颜色主题
    m_pythonLexer->setColor(QColor("#0000FF"), QsciLexerPython::Keyword);         // 关键字 - 蓝色
    m_pythonLexer->setColor(QColor("#008000"), QsciLexerPython::Comment);         // 注释 - 绿色
    m_pythonLexer->setColor(QColor("#FF0000"), QsciLexerPython::DoubleQuotedString); // 字符串 - 红色
    m_pythonLexer->setColor(QColor("#FF0000"), QsciLexerPython::SingleQuotedString); // 字符串 - 红色
    m_pythonLexer->setColor(QColor("#FF0000"), QsciLexerPython::TripleDoubleQuotedString); // 三引号字符串 - 红色
    m_pythonLexer->setColor(QColor("#FF0000"), QsciLexerPython::TripleSingleQuotedString); // 三引号字符串 - 红色
    m_pythonLexer->setColor(QColor("#800080"), QsciLexerPython::Number);          // 数字 - 紫色
    m_pythonLexer->setColor(QColor("#808080"), QsciLexerPython::Operator);        // 操作符 - 灰色
    m_pythonLexer->setColor(QColor("#000080"), QsciLexerPython::ClassName);       // 类名 - 深蓝色
    m_pythonLexer->setColor(QColor("#000080"), QsciLexerPython::FunctionMethodName); // 函数名 - 深蓝色
    m_pythonLexer->setColor(QColor("#008080"), QsciLexerPython::Decorator);       // 装饰器 - 青色
}

void PythonEditor::setupPythonAPIs()
{
    if (m_apis) {
        delete m_apis;
    }

    m_apis = new QsciAPIs(m_pythonLexer);

    // 添加Python关键字
    QStringList keywords = getPythonKeywords();
    for (const QString &keyword : keywords) {
        m_apis->add(keyword);
    }

    // 添加Python内置函数
    QStringList builtins = getPythonBuiltins();
    for (const QString &builtin : builtins) {
        m_apis->add(builtin);
    }

    // 添加Python模块
    QStringList modules = getPythonModules();
    for (const QString &module : modules) {
        m_apis->add(module);
    }

    // 添加自定义模块
    for (const QString &module : m_customModules) {
        m_apis->add(module);
    }

    m_apis->prepare();
}

void PythonEditor::setupPythonKeywords()
{
    // QsciLexerPython会自动处理关键字，这里可以进行额外的设置
}

QStringList PythonEditor::getPythonKeywords() const
{
    QStringList keywords;
    keywords << "and" << "as" << "assert" << "break" << "class" << "continue"
             << "def" << "del" << "elif" << "else" << "except" << "exec"
             << "finally" << "for" << "from" << "global" << "if" << "import"
             << "in" << "is" << "lambda" << "not" << "or" << "pass" << "print"
             << "raise" << "return" << "try" << "while" << "with" << "yield";

    if (m_pythonVersion == 3) {
        keywords << "nonlocal" << "True" << "False" << "None";
        keywords.removeOne("print"); // print在Python3中是函数，不是关键字
        keywords.removeOne("exec");  // exec在Python3中是函数，不是关键字
    } else {
        keywords << "exec" << "print";
    }

    return keywords;
}

QStringList PythonEditor::getPythonBuiltins() const
{
    QStringList builtins;
    builtins << "abs" << "all" << "any" << "ascii" << "bin" << "bool" << "bytearray"
             << "bytes" << "callable" << "chr" << "classmethod" << "compile" << "complex"
             << "delattr" << "dict" << "dir" << "divmod" << "enumerate" << "eval"
             << "exec" << "filter" << "float" << "format" << "frozenset" << "getattr"
             << "globals" << "hasattr" << "hash" << "help" << "hex" << "id" << "input"
             << "int" << "isinstance" << "issubclass" << "iter" << "len" << "list"
             << "locals" << "map" << "max" << "memoryview" << "min" << "next" << "object"
             << "oct" << "open" << "ord" << "pow" << "print" << "property" << "range"
             << "repr" << "reversed" << "round" << "set" << "setattr" << "slice" << "sorted"
             << "staticmethod" << "str" << "sum" << "super" << "tuple" << "type" << "vars"
             << "zip" << "__import__";

    if (m_pythonVersion == 2) {
        builtins << "basestring" << "cmp" << "execfile" << "file" << "long" << "raw_input"
                 << "reduce" << "reload" << "unicode" << "xrange";
    }

    return builtins;
}

QStringList PythonEditor::getPythonModules() const
{
    QStringList modules;
    modules << "os" << "sys" << "re" << "math" << "random" << "time" << "datetime"
            << "json" << "pickle" << "csv" << "sqlite3" << "urllib" << "http"
            << "threading" << "multiprocessing" << "collections" << "itertools"
            << "functools" << "operator" << "string" << "io" << "pathlib"
            << "logging" << "argparse" << "subprocess" << "shutil" << "glob"
            << "tempfile" << "gzip" << "zipfile" << "tarfile";

    return modules;
}
